package com.android.clinic.app.ui.search;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.DoctorInfo;
import com.android.clinic.app.entity.DoctorListInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.doctor.AskQuestionWithDoctorActivity;
import com.android.clinic.app.ui.doctor.DoctorDetailActivity;
import com.android.clinic.app.ui.doctor.ListAllDoctorActivity;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.BaseTextWatcher;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.LocalDataUtils;
import com.android.clinic.app.utils.Utils;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.kennyc.view.MultiStateView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by cheng on 2018/2/2.
 * 搜索
 */
public class SearchActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {

    private Intent intent;
    private LinearLayout laySearch;
    private TextView tvKeyWord;

    private String mKey = "无";

    private SwipeToLoadLayout swipeToLoadLayout;
    private ListView listView;
    private HospitalAdapter mAdapter;
    private int pageNum = 1; // 当前页数

    private LinearLayout layHistory;
    private FlowTagLayout historyFlowLay;
    private HistoryTagAdapter historyTagAdapter;
    private List<String> listHistory = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("");

        swipeToLoadLayout = (SwipeToLoadLayout) findViewById(R.id.swipeToLoadLayout);
        listView = (ListView) findViewById(R.id.swipe_target);
        laySearch = (LinearLayout) findViewById(R.id.layout_search);
        tvKeyWord = (TextView) findViewById(R.id.tv_keyword);
        layHistory = (LinearLayout) findViewById(R.id.layout_history_search);
        historyFlowLay = (FlowTagLayout) findViewById(R.id.history_flow_layout);

        initHistoryTags();
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        new Handler().postDelayed(() -> showInputMethod(), 100);

        etSearch.addTextChangedListener(new SearchTextWatcher());
        ivClose.setOnClickListener(v -> etSearch.setText(""));
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                searchKeyWord();
                return true;
            }
            return false;
        });

        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (!Utils.isEmpty(mAdapter.getItem(position).getHospitalName())) {
                intent = new Intent(SearchActivity.this, ListAllDoctorActivity.class);
                intent.putExtra("hospital", mAdapter.getItem(position).getHospitalName());
                startActivity(intent);
            } else {
                String doctorId = LocalDataUtils.getData(Constants.QUESTION_ID);
                // 如果doctorId不为null，说明该用户没有对医生进行提问
                if (!Utils.isEmpty(doctorId)) {
                    UIAlertView.alertDialog(SearchActivity.this, "操作提示",
                            "您还有一个提问待确认?", new UIAlertView.OnThemeDialogListener() {
                                @Override
                                public void OnDismissButton() {
                                    // 用户放弃提问，清除缓存，跳转到医生详情
                                    LocalDataUtils.removeData(Constants.QUESTION_ID);
                                    startDoctorDetailActivity(mAdapter.getItem(position));
                                }
                                @Override
                                public void OnSureButton() {
                                    // 去提问页面，继续提问
                                    Intent intent = new Intent(SearchActivity.this, AskQuestionWithDoctorActivity.class);
                                    intent.putExtra("doctorId", doctorId);
                                    startActivity(intent);
                                }
                            },"继续提问","放弃提问");

                } else {
                    startDoctorDetailActivity(mAdapter.getItem(position));
                }
            }

        });
    }

    /**
     * 跳转到医生详情
     * @param doctorInfo
     */
    private void startDoctorDetailActivity(DoctorInfo doctorInfo) {
        Intent intent = new Intent(SearchActivity.this, DoctorDetailActivity.class);
        intent.putExtra("doctorId", doctorInfo.getId());
        intent.putExtra("name", doctorInfo.getName());
        intent.putExtra("reservation", doctorInfo.getReservation());
        intent.putExtra("evaluation", doctorInfo.getEvaluation());
        startActivity(intent);
    }

    /**
     * 初始化历史搜索
     */
    private void initHistoryTags() {
        String local = LocalDataUtils.getData(Constants.LIST_HISTORY);
        if (!TextUtils.isEmpty(local.trim())) {
            Collections.addAll(listHistory, local.trim().split(","));
        }
        if (listHistory.size() > 0) {
            layHistory.setVisibility(View.VISIBLE);
            swipeToLoadLayout.setVisibility(View.GONE);
        }
        historyTagAdapter = new HistoryTagAdapter(listHistory);
        historyFlowLay.setAdapter(historyTagAdapter);
        historyTagAdapter.notifyDataSetChanged();
        historyFlowLay.setOnTagClickListener((parent, view, position) -> {
            mKey = historyTagAdapter.getItem(position);
            etSearch.setText(historyTagAdapter.getItem(position));
            searchKeyWord();
        });
    }

   private void getListSearch() {
       HttpClient.getHttpService().getListSearch(mKey, 10, pageNum)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<DoctorListInfo>() {
                    @Override
                    public void onSuccess(DoctorListInfo doctorListInfo) {
                        refreshComplete();
                        if (doctorListInfo.getResult().size() > 0) {
                            setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);

                            List<DoctorInfo> doctorInfoList = doctorListInfo.getResult();
                            int doctorSize = doctorInfoList.size();
                            for (int i = 0 ;i < doctorSize; i++) {
                                doctorInfoList.get(i).setReservation(String.valueOf((int)(Math.random()*1000)));
                                doctorInfoList.get(i).setEvaluation(String.valueOf((int)(Math.random()*100)));
                            }
                            mAdapter = new HospitalAdapter(doctorInfoList);
                            listView.setAdapter(mAdapter);
                        } else if (pageNum == 1) {
                            setMultiStateView(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        setMultiStateView(MultiStateView.VIEW_STATE_EMPTY);
                        refreshComplete();
                        showToast(message);
                    }
                });
   }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            // 关键字搜索
            case R.id.layout_goto_search:
                searchKeyWord();
                break;
            // 清除历史搜索
            case R.id.iv_clear_history:
                clearHistory();
                break;
        }
    }

    /**
     * 搜索关键字
     */
    private void searchKeyWord() {
        // 添加缓存
        if (!listHistory.contains(mKey)) {
            layHistory.setVisibility(View.GONE);
            swipeToLoadLayout.setVisibility(View.VISIBLE);
            int historySize = listHistory.size();
            listHistory.add(mKey);
            if (historySize == 10) {
                listHistory.remove(0);
            }
            // 正则替换java字符串中的中括号
            LocalDataUtils.saveData(Constants.LIST_HISTORY,
                    Arrays.toString(listHistory.toArray()).replaceAll("[ \\[ \\]]", "").trim());
        }
        hideKeyboard();
        if (null != mAdapter) {
            mAdapter.clear();
        }
        laySearch.setVisibility(View.GONE);
        swipeToLoadLayout.post(() -> swipeToLoadLayout.setRefreshing(true));
    }


    /**
     * 关键字搜索处理
     *
     * @author cheng
     *
     */
    private class SearchTextWatcher extends BaseTextWatcher {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mKey = s.toString().trim();
            if (!TextUtils.isEmpty(mKey.trim())) {
                layHistory.setVisibility(View.GONE);
                swipeToLoadLayout.setVisibility(View.VISIBLE);
                tvKeyWord.setText("搜索：\"" + mKey + "\"");
                setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);
                laySearch.setVisibility(View.VISIBLE);
            } else {
                laySearch.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            int editStart = etSearch.getSelectionEnd();
            etSearch.setSelection(editStart);
            if (editStart!=0){
                setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);
                ivClose.setVisibility(View.VISIBLE);
            }else{
                ivClose.setVisibility(View.GONE);
            }
        }
    }

    private void refreshComplete() {
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
        if (swipeToLoadLayout.isLoadingMore()) {
            swipeToLoadLayout.setLoadingMore(false);
        }
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        new Handler().postDelayed(this::getListSearch, 500);
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        new Handler().postDelayed(this::getListSearch, 500);
    }

    private class HospitalAdapter extends BaseAdapter {

        private List<DoctorInfo> mList;

        private static final int DOCTOR = 0;
        private static final int HOSPITAL = 1;

        public HospitalAdapter(List<DoctorInfo> list) {
            mList = list;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (!Utils.isEmpty(mList.get(position).getHospitalName())) {
                return HOSPITAL;
            } else {
                return DOCTOR;
            }
        }

        @Override
        public DoctorInfo getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int typeIndex = getItemViewType(position);
            if (typeIndex == DOCTOR) {
                ViewHolder holder;
                if (convertView == null) {
                    convertView = LinearLayout.inflate(SearchActivity.this, R.layout.item_list_famous_doctor, null);
                    holder = new ViewHolder();
                    holder.ivHead = (ImageView) convertView.findViewById(R.id.iv_head);
                    holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                    holder.tvPosition = (TextView) convertView.findViewById(R.id.tv_position);
                    holder.tvHospital = (TextView) convertView.findViewById(R.id.tv_hospital);
                    holder.layLabel = (LinearLayout) convertView.findViewById(R.id.layout_label);
                    holder.tvDefaultName = (TextView) convertView.findViewById(R.id.tv_default_name);
                    holder.layDefault = (FrameLayout) convertView.findViewById(R.id.layout_default);
                    holder.tvReservation = (TextView) convertView.findViewById(R.id.tv_reservation);
                    holder.tvEvaluation = (TextView) convertView.findViewById(R.id.tv_evaluation);
                    holder.tvDeptName = (TextView) convertView.findViewById(R.id.tv_dept_name);
                    holder.tvInquirePrice = (TextView) convertView.findViewById(R.id.tv_inquire_price);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                holder.tvName.setText(getItem(position).getName());
                holder.tvHospital.setText(getItem(position).getHospital());
                holder.tvPosition.setText(getItem(position).getPosition());
                holder.tvReservation.setText(getItem(position).getReservation());
                holder.tvEvaluation.setText(getItem(position).getEvaluation());
                holder.tvDeptName.setText(getItem(position).getDeptName());
                holder.tvInquirePrice.setText(getString(R.string.doctor_inquire_price_text, getItem(position).getInquirePrice()));

                if (getItem(position).getImgUrl().contains(".jpg") && !Utils.isEmpty(getItem(position).getImgUrl())) {
                    holder.ivHead.setVisibility(View.VISIBLE);
                    holder.layDefault.setVisibility(View.GONE);
                    ImageLoaderUtils.getInstance().loadHeadImage(getItem(position).getImgUrl(), holder.ivHead);
                } else {
                    holder.ivHead.setVisibility(View.GONE);
                    holder.layDefault.setVisibility(View.VISIBLE);
                    holder.tvDefaultName.setText(getItem(position).getName());
                }

                if (!Utils.isEmpty(getItem(position).getLabel())) {
                    holder.layLabel.setVisibility(View.VISIBLE);
                    String[] labelArray = getItem(position).getLabel().split(",");
                    int labelSize;
                    if (labelArray.length > 3) {
                        labelSize = 3;
                    } else {
                        labelSize = labelArray.length;
                    }
                    holder.layLabel.removeAllViews();
                    for (int i = 0; i < labelSize; i++) {
                        View labelView = LinearLayout.inflate(SearchActivity.this,
                                R.layout.item_list_famous_doctor_label, null);

                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp.setMargins(0, 0, 10, 0);
                        labelView.setLayoutParams(lp);

                        TextView tvLabel = (TextView) labelView.findViewById(R.id.tv_label);
                        tvLabel.setText(labelArray[i]);
                        holder.layLabel.addView(labelView);
                    }
                } else {
                    holder.layLabel.setVisibility(View.GONE);
                }

            } else {
                HospitalViewHolder hospitalHolder;
                if (convertView == null) {
                    convertView = LinearLayout.inflate(SearchActivity.this, R.layout.item_list_hospital, null);
                    hospitalHolder = new HospitalViewHolder();
                    hospitalHolder.ivPic = (ImageView) convertView.findViewById(R.id.iv_pic);
                    hospitalHolder.tvHospital = (TextView) convertView.findViewById(R.id.tv_hospital);
                    hospitalHolder.tvReserveNum = (TextView) convertView.findViewById(R.id.tv_reserve_num);
                    hospitalHolder.tvDefaultName = (TextView) convertView.findViewById(R.id.tv_default_name);
                    hospitalHolder.layDefault = (FrameLayout) convertView.findViewById(R.id.layout_default);
                    convertView.setTag(hospitalHolder);
                } else {
                    hospitalHolder = (HospitalViewHolder) convertView.getTag();
                }
                hospitalHolder.tvHospital.setText(getItem(position).getHospitalName());
                hospitalHolder.tvReserveNum.setText(String.valueOf((int)(Math.random()*1000)));

                if (getItem(position).getImgUrl().contains(".jpg") || getItem(position).getImgUrl().contains(".png")
                        && !Utils.isEmpty(getItem(position).getImgUrl())) {
                    hospitalHolder.ivPic.setVisibility(View.VISIBLE);
                    hospitalHolder.layDefault.setVisibility(View.GONE);
                    ImageLoaderUtils.getInstance().loadNormalImage(getItem(position).getImgUrl(), hospitalHolder.ivPic);
                } else {
                    hospitalHolder.ivPic.setVisibility(View.GONE);
                    hospitalHolder.layDefault.setVisibility(View.VISIBLE);
                    hospitalHolder.tvDefaultName.setText(getItem(position).getHospitalName());
                }

            }
            return convertView;
        }

        private void clear() {
            mList.clear();
            notifyDataSetChanged();
        }

        class ViewHolder {
            ImageView ivHead;
            TextView tvName, tvPosition, tvHospital, tvDefaultName, tvReservation, tvEvaluation, tvDeptName, tvInquirePrice;
            LinearLayout layLabel;
            FrameLayout layDefault;
        }

        class HospitalViewHolder {
            ImageView ivPic;
            TextView tvHospital, tvReserveNum, tvDefaultName;
            FrameLayout layDefault;
        }
    }

    private class HistoryTagAdapter extends BaseAdapter implements OnInitSelectedPosition {

        private List<String> dataList = new ArrayList<>();
        private int position;

        private HistoryTagAdapter(List<String> data) {
            dataList = data;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public String getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_history_tag_textview, null);
            TextView textView = (TextView) view.findViewById(R.id.tv_tag);
            String t = dataList.get(position).trim();
            textView.setText(t);
            return view;
        }

        public void setSelected(int p) {
            position = p;
        }

        public void updateHistoryKeyword(List<String> data) {
            dataList = data;
            notifyDataSetChanged();
        }

        @Override
        public boolean isSelectedPosition(int poi) {
            if (poi == position) {
                return true;
            }
            return false;
        }
    }

    /**
     * 清除历史搜索
     */
    public void clearHistory() {
        layHistory.setVisibility(View.GONE);
        listHistory.clear();
//        LocalDataUtils.removeData(Constants.LIST_HISTORY);
    }

}
